package com.charley.icloud.admin.webapps.sysdict.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.charley.icloud.admin.webapps.sysdict.dao.SysDictMapper;
import com.charley.icloud.admin.webapps.sysdict.pojo.entity.SysDictDO;
import com.charley.icloud.admin.webapps.sysdict.pojo.model.SysDictVO;
import com.charley.icloud.admin.webapps.sysdict.service.SysDictService;
import com.charley.icloud.datasource.page.MybatisPageHelper;
import com.charley.icloud.datasource.page.PageRequest;
import com.charley.icloud.datasource.page.PageResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SysDictServiceImpl implements SysDictService {

    @Resource
    private SysDictMapper sysDictMapper;

    @Override
    public int save(SysDictDO record) {
        // 新增
        if (record.getId() == null || record.getId() == 0) {
            record.setCreateBy("System");
            record.setCreateTime(new Date());
            return sysDictMapper.insertSelective(record);
        }
        // 修改
        record.setLastUpdateBy("System");
        record.setLastUpdateTime(new Date());
        return sysDictMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int delete(SysDictDO record) {
        return sysDictMapper.deleteByPrimaryKey(record);
    }

    @Override
    public int delete(List<SysDictDO> records) {
        for (SysDictDO record : records) {
            record.setLastUpdateBy("System");
            record.setLastUpdateTime(new Date());
            delete(record);
        }
        return 1;
    }

    @Override
    public SysDictDO findById(Long id) {
        return sysDictMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult findPage(PageRequest pageRequest) {
        Object label = pageRequest.getParam("label");
        if (label != null) {
            return MybatisPageHelper.findPage(pageRequest, sysDictMapper, "findPageByLabel", label);
        }
        return MybatisPageHelper.findPage(pageRequest, sysDictMapper);
    }

    @Override
    public List<SysDictVO> findByLabel(String label) {
        List<SysDictDO> sysDicts = sysDictMapper.findByLabel(label);

        List<SysDictVO> sysDictVOS = new ArrayList<>();
        for (SysDictDO sysDict : sysDicts) {
            SysDictVO sysDictVO = new SysDictVO();
            BeanUtil.copyProperties(sysDict, sysDictVO, CopyOptions.create().ignoreCase().ignoreNullValue());
            sysDictVOS.add(sysDictVO);
        }

        return sysDictVOS;
    }

}
